import 'dart:convert';

import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/pages/splash/model_api_config.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/shared/shared_export.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedStorage {
  static final SharedStorage _instance = SharedStorage._();

  factory SharedStorage() => _instance;

  SharedStorage._();

  late SharedPreferences prefs;

  Future initShareStorage() async {
    prefs = await SharedPreferences.getInstance();
  }

  //第一次启动
  String? getDeviceId() {
    return prefs.getString(SharedKey.deviceId);
  }

  ModelApiConfig getApiConfig() {
    try {
      String value = prefs.getString(SharedKey.aipConfig) ?? '{}';
      Map<String, dynamic> map = jsonDecode(value);
      ModelApiConfig apiConfig = ModelApiConfig.fromJson(map);
      clog('getApiConfig  ${apiConfig.toJson()}');
      return (apiConfig.api ?? []).isNotEmpty
          ? apiConfig
          : AppConfig.defaultApiConfig;
    } catch (_) {
      return AppConfig.defaultApiConfig;
    }
  }

  setApiConfig(ModelApiConfig apiConfig) async {
    clog('setApiConfig  ${apiConfig.toJson()}');
   await prefs.setString(SharedKey.aipConfig, jsonEncode(apiConfig.toJson()));
  }
}
